﻿/*
* Copyright (c) 2012 Kyle Hayward
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;

using Tao.OpenGl;

using OptixDotNet;
using OptixDotNet.Traversal;
using OptixDotNet.Math;
using OptixDotNet.Utils;

using OptixDotNetUtils;

using OptixTypes = OptixDotNet.Math;

namespace Sample
{
    public class TraversalSample : OptixForm
    {
        const int NumOutputs = 2;

        Traversal mTraversal;

        float[] mDepths;
        Vector3[] mNormals;
        bool mUpdateDepth = true;
        bool mUpdateNormals = true;

        int mOutput = 0;
        string mOutputStr = "Depth";

        public TraversalSample()
        {
            //Ensure that we have a valid Nvidia GPU
            Utils.TryDetectGPUCompatibility();
        }

        protected override void Initialize()
        {
            string modelPath = Path.GetFullPath( "../../Assets/Models/sibenik.obj" );
            string accelCache = "traversal.sibenik.obj.accel";

            /*-----------------------------------------------
             * Create Context and Traversal context
             *-----------------------------------------------*/
            Context = new Context();
            mTraversal = new Traversal( Context, QueryType.ClosestHit, RayFormat.OriginDirectionInterleaved, TriFormat.Mesh, 
                                        TraversalOutput.Normal, InitOptions.None );

            mTraversal.NumCpuThreads = Context.CpuNumThreads;

            /*-----------------------------------------------
             * Load mesh data
             *-----------------------------------------------*/
            OptixOBJLoader model = new OptixOBJLoader( modelPath, Context, null, null );

            //OBJLoader normally automatically creates Geometry, GeometryInstances, and GeometryGroups for Optix
            //but the Traversal API doesn't use that, so turn that off
            model.ParseMaterials = false;
            model.ParseNormals = false;
            model.GenerateNormals = false;
            model.GenerateGeometry = false;
            model.LoadContent();
            SetCamera( model.BBox );

            //we copy the data here or else the GC would clean up a model.Vertices.ToArray() for example
            Vector3[] verts = new Vector3[ model.Positions.Count ];
            Int3[] tris = new Int3[ model.Groups[ 0 ].VIndices.Count ];

            model.Positions.CopyTo( verts );
            model.Groups[ 0 ].VIndices.CopyTo( tris );

            mTraversal.SetMesh<Vector3, Int3>( (uint)verts.Length, verts, 
                                               (uint)tris.Length, tris );

            /*-----------------------------------------------
             * Create rays
             *-----------------------------------------------*/
            int numRays = Width * Height;
            mTraversal.SetRayData<Ray>( CreateRays() );

            /*-----------------------------------------------
             * Preprocess data
             *-----------------------------------------------*/
            //check to see if we can load a previously saved acceleration data
            if ( File.Exists( accelCache ) )
            {
                BufferStream accelData = new BufferStream( File.OpenRead( accelCache ) );
                mTraversal.AccelData = accelData;
            }

            Console.Write( "Compiling Traversal scene... " );
            float start = Time.GetTimeInSecs();

            mTraversal.Preprocess();

            Console.WriteLine( "{0:0.00}s", Time.GetTimeInSecs() - start );

            //save out accel data
            mTraversal.AccelData.Save( accelCache );

            /*-----------------------------------------------
             * Alloc space for outputs
             *-----------------------------------------------*/
            mDepths = new float[ numRays ];
            mNormals = new Vector3[ numRays ];

            RaysTracedPerFrame = numRays;
            model = null;
        }

        private Ray[] CreateRays()
        {
            Ray[] rays = new Ray[ Width * Height ];

            for ( int x = 0; x < Width; x++ )
            {
                for ( int y = 0; y < Height; y++ )
                {
                    Vector2 d = new Vector2( x, y ) / new Vector2( Width, Height ) * 2.0f - 1.0f;

                    Ray ray;
                    ray.Origin = Camera.Position;
                    ray.Direction = d.X * Camera.Right + d.Y * Camera.Up + Camera.Look;
                    ray.Direction.Normalize();

                    rays[ y * Width + x ] = ray;
                }
            }

            return rays;
        }

        private void SetCamera( BoundingBox box )
        {
            Camera = new Camera();
            Camera.Aspect = (float)Width / (float)Height;
            Camera.Fov = 60.0f;
            Camera.RotationVel = 100.0f;
            Camera.TranslationVel = 500.0f;

            //sibenik camera position
            Camera.LookAt( new Vector3( -19.5f, -10.3f, .8f ), new Vector3( 0.0f, -13.3f, .8f ), Vector3.UnitY );
            //Camera.CenterOnBoundingBox( box );
        }

        protected override void RayTrace()
        {
            mTraversal.Traverse();
        }

        protected override void Display()
        {
            switch ( mOutput )
            {
                case 0:
                    {
                        mOutputStr = "Depth";

                        if ( mUpdateDepth )
                        {
                            float maxDepth = -1.0f;
                            TraversalStream<TraversalResult> stream = mTraversal.MapResults();
                            for ( int i = 0; i < stream.Length; i++ )
                            {
                                TraversalResult result = stream.Stream.Read<TraversalResult>();
                                mDepths[ i ] = result.T;

                                maxDepth = Math.Max( maxDepth, mDepths[ i ] );
                            }

                            for ( int i = 0; i < stream.Length; i++ )
                            {
                                mDepths[ i ] /= maxDepth;
                            }
                            mTraversal.UnmapResults();

                            mUpdateDepth = false;
                        }

                        Gl.glDrawPixels( Width, Height, Gl.GL_LUMINANCE, Gl.GL_FLOAT, mDepths );
                    }
                    break;
                case 1:
                    {
                        mOutputStr = "Normals";

                        if ( mUpdateNormals )
                        {
                            mTraversal.GetNormalOutput( mNormals );

                            //bias/scale normals so we don't have black
                            for ( int i = 0; i < mNormals.Length; i++ )
                            {
                                mNormals[ i ] = mNormals[ i ] * .5f + .5f;
                            }

                            mUpdateNormals = false;
                        }

                        Gl.glDrawPixels( Width, Height, Gl.GL_RGB, Gl.GL_FLOAT, mNormals );
                    }
                    break;
                default:
                    break;
            }            

            DrawText( 15, 30, "Press 'D' to toggle output display: " + mOutputStr ); 
        }

        protected override void GLControl_KeyUp( object sender, KeyEventArgs e )
        {
            base.GLControl_KeyUp( sender, e );

            switch ( e.KeyCode )
            {
                case Keys.D:
                    mOutput = ( mOutput + 1 ) % NumOutputs; 
                    break;
                default:
                    break;
            }
        }

        protected override void Shutdown()
        {
            mTraversal.Destroy();

            base.Shutdown();
        }
    }
}
